package at.evonfc.view;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import at.evonfc.bl.DateUtils;
import at.evonfc.bl.MenuUtils;
import at.evonfc.bl.MyExpandableListView;
import at.evonfc.data.Cart;
import at.evonfc.data.ChildItem;
import at.evonfc.data.Device;
import at.evonfc.data.ParentItem;
import at.evonfc.data.Rental;
import at.evonfc.data.Employee;
import at.evonfc.listofdeviceswithnfc.R;

public class HomeActivity extends Activity {
	public final static String ACTIVITY_NAME = "HOME_ACTIVITY";
	
	private Menu menu;
	private ExpandableListView elvBorrowedDevices;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		
		MainActivity.active_activity = HomeActivity.ACTIVITY_NAME;

		Employee user = MainActivity.user;
		//create the User instance
		//get the TextView and change the name of the user
		TextView view = (TextView)findViewById(R.id.tvUser);
		view.setText(getString(R.string.tv_welcomeHome).replace("#user#", user.getEmployeeName()));
		
		//get the ListView
		this.elvBorrowedDevices = (ExpandableListView)findViewById(R.id.elvBorrowedDevices);
	}
	
	private void updateUI() {

		Cart.removeUnused();
		
		//get the scroll view for the borrowed Devices
		
		try {
			List<Rental> borrowedDevices = MainActivity.user.getBorrowedDevices();
			if(borrowedDevices != null && !borrowedDevices.isEmpty()) {
				Collections.sort(borrowedDevices, new Comparator<Rental>() {
					@Override
					public int compare(Rental lhs, Rental rhs) {
						return lhs.getFromDate().compareTo(rhs.getFromDate());
					}
				});
				
				ArrayList<ParentItem> parents = new ArrayList<ParentItem>();
				
				HashMap<Device, ParentItem> deviceFormatMap = new HashMap<Device, ParentItem>();
				for(Rental dev : borrowedDevices) {
					if(deviceFormatMap.containsKey(dev.getDevice())) {
						ParentItem parent = deviceFormatMap.get(dev.getDevice());
						if(dev.getFromDate().before(Calendar.getInstance())) {
							parent.getChildItemList().add(new ChildItem("derzeit ausgeborgt"));
						} else {
							if(dev.getEndDate() != null) {
								parent.getChildItemList().add(new ChildItem("reserviert: " + DateUtils.getInstance().convertToDateString(dev.getFromDate()) + " - " + DateUtils.getInstance().convertToDateString(dev.getEndDate())));
							} else {
								parent.getChildItemList().add(new ChildItem("reserviert: " + DateUtils.getInstance().convertToDateString(dev.getFromDate()) + " - n/a"));
							}
						}
						deviceFormatMap.put(dev.getDevice(), parent);
					} else {
						ParentItem parent = new ParentItem(dev.getDevice().getName());
						parents.add(parent);
						if(dev.getFromDate().before(Calendar.getInstance())) {
							if(dev.getEndDate() != null) {
								parent.getChildItemList().add(new ChildItem("derzeit ausgeborgt bis " + DateUtils.getInstance().convertToDateString(dev.getEndDate())));
							} else {
								parent.getChildItemList().add(new ChildItem("derzeit ausgeborgt bis n/a"));
							}
						} else {
							if(dev.getEndDate() != null) {
								parent.getChildItemList().add(new ChildItem("reserviert: " + DateUtils.getInstance().convertToDateString(dev.getFromDate()) + " - " + DateUtils.getInstance().convertToDateString(dev.getEndDate())));
							} else {
								parent.getChildItemList().add(new ChildItem("reserviert: " + DateUtils.getInstance().convertToDateString(dev.getFromDate()) + " - n/a"));
							}
						}
						deviceFormatMap.put(dev.getDevice(), parent);
					}
				}

				//create a Layout which holds the views
				MyExpandableListView myList = new MyExpandableListView(this, parents);
				elvBorrowedDevices.setAdapter(myList);
				elvBorrowedDevices.setGroupIndicator(this.getResources().getDrawable(
	                    R.drawable.group_indicator));
				findViewById(R.id.tvBorrowedDevicesBanner).setVisibility(View.INVISIBLE);

				//set the return button invisible, if there are no currently borrowed devices
				boolean showReturnButton = false;
				for(Rental rental : borrowedDevices) {
					if(rental.getFromDate().before(Calendar.getInstance())) {
						showReturnButton = true;
					}
				}
				if(!showReturnButton) {
					findViewById(R.id.btReturn).setVisibility(View.INVISIBLE);
				}
			} else {
				findViewById(R.id.tvBorrowedDevicesBanner).setVisibility(View.VISIBLE);
				findViewById(R.id.btReturn).setVisibility(View.INVISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("err", e.toString());
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MainActivity.active_activity = HomeActivity.ACTIVITY_NAME;

		if(menu != null) {
			menu.clear();
			onCreateOptionsMenu(menu);
		}
		
		updateUI();
	}

	/**
	 * Disable the back button.
	 * The user will not be able to get back.
	 */
	@Override
	public void onBackPressed() {
	}
	
	
	public void onBorrowDevice(View view) {
		//open window for borrowing devices
        Intent intent = new Intent(this, BorrowActivity.class);
        //start the BorrowActivity
        startActivity(intent);
	}
	
	public void onReserveDevice(View view) {
		//open window for reserving devices
        Intent intent = new Intent(this, BorrowActivity.class);
        //start the BorrowActivity with the reserve extra
        intent.putExtra(BorrowActivity.RESERVE_MODE, true);
        startActivity(intent);
	}
	
	public void onReturnDevice(View view) {
		//open window for returning devices
        Intent intent = new Intent(this, ReturnDeviceActivity.class);
        //start the ReturnDeviceActivity
        startActivity(intent);
	}
	
	public void onLogout(MenuItem item) {
		MenuUtils.getInstance().onLogout(this);
	}
	
	public void onCartClick(MenuItem item) {
		MenuUtils.getInstance().onCartClick(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.menu = menu;
	    MenuInflater inflater = getMenuInflater();
	    if(Cart.hasElements()) {
	    	inflater.inflate(R.menu.cart_new, menu);
	    } else {
	    	inflater.inflate(R.menu.cart_logout, menu);
	    }
	    return true;
	}
}
